//
//  FileSaveOpration.swift
//  CMCCIOTSwift
//
//  Created by xukai on 2017/4/23.
//  Copyright © 2017年 isoftstone. All rights reserved.
//

import UIKit
import Foundation
class FileSaveOpration : NSObject{
    
    var userList : NSObject?
    //单例模式
    static var shared:FileSaveOpration {
        struct Static {
            static let instance: FileSaveOpration = FileSaveOpration()
        }
        return Static.instance
    }
    
    override init() {
    super.init()
    }
    
        //保存数据
        func saveData() {
            let data = NSMutableData()
            //申明一个归档处理对象
            let archiver = NSKeyedArchiver(forWritingWith: data)
            //将lists以对应Checklist关键字进行编码
            archiver.encode(userList, forKey: NSStringFromClass(userList as! AnyClass).appending("List"))
            //编码结束
            archiver.finishEncoding()
            //数据写入
            data.write(toFile: dataFilePath(), atomically: true)
        }
        
        //读取数据
        func loadData() {
            //获取本地数据文件地址
            let path = self.dataFilePath()
            //声明文件管理器
            let defaultManager = FileManager()
            //通过文件地址判断数据文件是否存在
            if defaultManager.fileExists(atPath: path) {
                //读取文件数据
                let data = NSData(contentsOfFile: path)
                //解码器
                let unarchiver = NSKeyedUnarchiver(forReadingWith: data! as Data)
                //通过归档时设置的关键字Checklist还原lists
                userList = unarchiver.decodeObject(forKey: NSStringFromClass(userList as! AnyClass).appending("List"))  as? NSObject
                //结束解码
                unarchiver.finishDecoding()
            }
        }
        
        //获取沙盒文件夹路径
        func documentsDirectory()->String {
            let paths = NSSearchPathForDirectoriesInDomains(
                FileManager.SearchPathDirectory.documentationDirectory,FileManager.SearchPathDomainMask.userDomainMask,true)
            let documentsDirectory:String = paths.first!
            return documentsDirectory
        }
        
        //获取数据文件地址
        func dataFilePath ()->String{
            
            return self.documentsDirectory().appending(NSStringFromClass(userList as! AnyClass).appending("List"))
        
        }
    
    
}
